package club.baimahu.pencil.domain.entity.event;

import club.baimahu.pencil.exception.EventException;

import java.util.List;
import java.util.concurrent.*;

public class SimpleStockEventMulticaster implements  StockEventMulticaster{

    ExecutorService executorService = Executors.newFixedThreadPool(2);

    private List<StockEventListener> stockEventListenerList;



    @Override
    public void multicastEvent(StockEvent event) {
        for(StockEventListener stockEventListener : stockEventListenerList){
            if(stockEventListener.support(event)){
                //stockEventListener.onEvent(event);
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        stockEventListener.onEvent(event);
                    }
                });
            }
        }
    }

    @Override
    public synchronized void addListener(StockEventListener stockEventListener) {
        if(stockEventListener == null){
            throw new EventException("stockEventListener can not be null");
        }
        if(stockEventListenerList == null){
            stockEventListenerList = new CopyOnWriteArrayList<>();
        }
        if(stockEventListener == null){

        }
        stockEventListenerList.add(stockEventListener);

    }
}
